<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'
import router from '@/router'
import {
  adminGetNotificationDraftService,
  adminPublishNotificationDraftService,
  adminSaveNotificationDraftService
} from '@/api/admin'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<Editor | null>(null)

// 内容 HTML
const form = ref({
  title: '',
  content: ''
})

const mode = ref('default')

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) {
    try {
      editor.destroy() // 确保销毁编辑器
      console.log('Editor destroyed successfully.')
    } catch (err) {
      console.error('Error during editor destruction:', err)
    }
  }
})

// 编辑器实例创建完成时的回调
const handleCreated = (editor: Editor) => {
  editorRef.value = editor // 记录 editor 实例
  console.log('Editor created:', editor)
}

// 保存草稿并退出
const saveAndExit = async () => {
  try {
    await adminSaveNotificationDraftService(form.value)
    ElMessage.success('保存成功！')
    await router.push('/teacher/notification')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试！')
  }
}

// 获取草稿数据
const getDrafts = async () => {
  try {
    const res = await adminGetNotificationDraftService()
    if (res.data && res.data.data) {
      form.value = res.data.data
    } else {
      ElMessage.warning('草稿数据为空')
    }
  } catch (error) {
    console.error('获取草稿失败:', error)
    ElMessage.error('获取草稿失败，请稍后重试！')
  }
}

// 发布草稿
const publish = async () => {
  try {
    await adminPublishNotificationDraftService(form.value)
    ElMessage.success('发布成功！')
    await router.push('/teacher/notification')
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败，请稍后重试！')
  }
}

// 初始化草稿数据
onMounted(() => {
  getDrafts()
})
</script>

<template>
  <div id="main-notificationCreate">
    <h1>公告发布</h1>
    <el-input
      placeholder="标题"
      style="height: 50px; margin-top: 10px; font: bold 20px Microsoft YaHei"
      v-model="form.title"
    ></el-input>
    <div style="border: 1px solid #ccc; margin: 10px 0">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="form.content"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    <div class="bt-area">
      <el-button type="primary" @click="publish">发布</el-button>
      <el-button type="warning" @click="saveAndExit">保存并退出</el-button>
    </div>
  </div>
</template>

<style scoped>
#main-notificationCreate {
  padding: 10px;
  margin: 10px;
}

.bt-area {
  display: flex;
  gap: 10px;
}
</style>
